package com.csx.governance.traffic.adapter.outbound;

import cn.hutool.core.lang.Assert;
import com.csx.governance.traffic.core.context.TrafficMessage;
import com.csx.governance.traffic.core.context.TrafficRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerInterceptor;
import org.springframework.cloud.client.loadbalancer.LoadBalancerRequestFactory;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpResponse;

import java.io.IOException;
import java.net.URI;

/**
 * @author cuisongxu
 * @date 2023/4/2 11:50
 */
public class TrafficLoadBalancerInterceptor extends LoadBalancerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(TrafficLoadBalancerInterceptor.class);

    private LoadBalancerClient loadBalancerClient;

    private LoadBalancerRequestFactory loadBalancerRequestFactory;

    public TrafficLoadBalancerInterceptor(LoadBalancerClient loadBalancer, LoadBalancerRequestFactory requestFactory) {
        super(loadBalancer, requestFactory);
    }

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        if(!(request instanceof TrafficRequest)) {
            logger.debug("This request will not join full link grayscale");
            return super.intercept(request, body, execution);
        }
        final URI originUri = request.getURI();
        String serviceName = originUri.getHost();
        Assert.notNull(serviceName, "Request URL don't contain a valid hostname: " + originUri);
        return loadBalancerClient.execute(serviceName, new TrafficLoadBalancerRequest<>((TrafficMessage) request, this.loadBalancerRequestFactory.createRequest(request, body, execution)));
    }
}
